EASY
Given two promises promise1 and promise2, return a new promise.
promise1 and promise2 will both resolve with a number. The returned promise should resolve with the sum of the two numbers.
接受兩個Promise (Promise1 和 Promise2)作為參數,返回一個新的 Promise。
Promise1 和 Promise2 都會解析出一個數字。 返回的Promise解析應為兩個數字的總和
解決方案1: 等兩個promise解析完畢後用promise.all()取得陣列,再用reduce把結果進行加總。
const addTwoPromises = async(promise1,promise2)=>{
let resultAry = await Promise.all([promise1, promise2]);
let sum = resultAry.reduce((acc,cur)=>acc+cur,0);
return sum;
}
解決方案2: 利用解構賦值讓程式碼更加直觀
const addTwoPromises = async(promise1,promise2)=>{
const [value1, value2] = await Promise.all([promise1, promise2]);
return value1 + value2;
}
async\await
const test1Promise1 = new Promise(resolve => setTimeout(() => resolve(2), 20));
const test1Promise2 = new Promise(resolve => setTimeout(() => resolve(5), 60));
addTwoPromises(test1Promise1, test1Promise2) //PromiseResult:7
const test2Promise1 = new Promise(resolve => setTimeout(() => resolve(10), 50));
const test2Promise2 = new Promise(resolve => setTimeout(() => resolve(-12), 30));
addTwoPromises(test2Promise1, test2Promise2) //PromiseResult:-2